package safeCommitter.test.finder.all;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IParent;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.core.JavaProject;

import safeCommitter.model.adpters.ISCTest;
import safeCommitter.model.adpters.SCFullClazzTest;

public class AllTestFinder {
	private final String testPath = "";

	public AllTestFinder() {
		// testPath =
		// Activator.getDefault().getPreferenceStore().getString(
		// SCPreferenceConstants.P_SEARCH_PATH);
	}

	public Set<ISCTest> findAll(final IJavaProject javaProject) {
		Set<ISCTest> returnSet = new HashSet<ISCTest>();
		String[] testPaths = testPath.split(",");
		if (testPath.equals("")) {
			return Collections.emptySet();
		}
		for (String path : testPaths) {
			returnSet.addAll(findSCTestFromPath(path, javaProject));
		}
		return returnSet;

	}

	private Collection<ISCTest> findSCTestFromPath(final String path,
			final IJavaProject javaProject) {
		IPackageFragmentRoot packageRoot = ((JavaProject) javaProject)
				.getPackageFragmentRoot(new Path(path));
		Set<ISCTest> returnSet = new HashSet<ISCTest>();
		try {
			recursiveSearch(packageRoot, returnSet);
		} catch (JavaModelException e) {
			e.printStackTrace();
		}
		return returnSet;

	}

	private Collection<ISCTest> recursiveSearch(final IJavaElement element,
			final Set<ISCTest> returnSet) throws JavaModelException {
		if (element instanceof ICompilationUnit) {
			returnSet.add(new SCFullClazzTest((ICompilationUnit) element));
		} else if (element instanceof IParent) {
			IJavaElement[] elements = ((IParent) element).getChildren();
			for (IJavaElement e : elements) {
				recursiveSearch(e, returnSet);
			}
		}
		return returnSet;

	}

}
